<template>
  <el-form v-loading="loading" ref="form" :model="form">
    <el-form-item prop="items" >
      <el-tree
      ref="tree"
        :data="data"
        node-key="id"
        show-checkbox
        default-expand-all
        :default-checked-keys="defaultSelected"
        :props="defaultProps"
      >
        <!-- :default-expanded-keys="[2, 3]"
      :default-checked-keys="[5]" -->
      </el-tree>
    </el-form-item>
    <el-form-item>
      <el-button @click="submit">提交</el-button>
      <el-button @click="clear">清空</el-button>
    </el-form-item>
  </el-form>
</template>
<script lang="ts">
import { getRoleMenus, allocateRoleMenus } from '@/services/menu'
import { HasId, ID } from '@/types'
import { wrapAsyncWithLoading } from '@/utils/helper'
import { Tree } from 'element-ui/types'
import Vue from 'vue'

interface Item extends HasId {
  selected: boolean;
  subMenuList: Item[];
}

function getSelectedIds (nodeItems: Item[], selectedIds: ID[] = []) {
  for (const item of nodeItems) {
    if (item.selected) {
      selectedIds.push(item.id)
    }
    if (item.subMenuList) {
      getSelectedIds(item.subMenuList, selectedIds)
    }
  }
  return selectedIds
}
export default Vue.extend({
  name: 'role-alloc-menu',
  props: ['id'],
  data () {
    return {
      loading: false,
      form: { items: [] },
      data: [
        // id,label,children
      ] as Item[],
      defaultSelected: [] as ID[],
      defaultProps: {
        children: 'subMenuList',
        label: 'name'
      }
    }
  },
  created () {
    wrapAsyncWithLoading(this, 'loading', 'loadData')
    wrapAsyncWithLoading(this, 'loading', 'submit')
    this.loadData()
  },
  methods: {
    async loadData () {
      const { data } = await getRoleMenus(this.id)
      if (data.code === '000000') {
        this.defaultSelected = getSelectedIds(data.data as Item[])
        this.data = data.data
        return
      }
      this.$message.error('获取菜单信息失败')
    },
    clear () {
      (this.$refs.tree as Tree).setCheckedKeys([])
    },
    async submit () {
      const checkedKeys = (this.$refs.tree as Tree).getCheckedKeys()
      const { data } = await allocateRoleMenus(this.id, checkedKeys)
      if (data.code === '000000') {
        this.$message.success('已修改')
      }
    }
  }
})
// todo 测试碰到：无权操作
</script>
